MODULE fun
CONTAINS
DOUBLE PRECISION FUNCTION fact(n)
IMPLICIT NONE

INTEGER,INTENT(IN) :: n
INTEGER :: i
DOUBLE PRECISION :: p=1
p=1
DO i=1,n
    p=i*p
END DO
fact=p
END FUNCTION fact

RECURSIVE SUBROUTINE permute(particles,pos,cnt,table)
IMPLICIT NONE
INTEGER,INTENT(IN) :: particles,pos
INTEGER,INTENT(INOUT) :: cnt
INTEGER,INTENT(INOUT),ALLOCATABLE,DIMENSION(:,:) :: table
INTEGER :: i,j,k
INTEGER :: st_i,st_f
INTEGER ::ch

IF(particles==0) THEN
  table(cnt,pos)=0
  cnt=cnt+1
  !print *,'b',(table(cnt-1,i),i=1,5)
  RETURN
END IF

IF(pos==1) THEN
  table(cnt,pos)=particles
  cnt=cnt+1
 ! print *,'a',(table(cnt-1,i),i=1,5)
  RETURN
END IF

DO i=particles,0,-1
  st_i=cnt
  table(cnt,pos)=i
  call permute(particles-i,pos-1,cnt,table)
  st_f=cnt
    DO j=st_i,st_f-1
      table(j,pos)=i
      !print *,j,(table(j,k),k=1,5)
    end do
    !read *,ch
END DO

END SUBROUTINE permute

SUBROUTINE generatePermutations(n,table)
IMPLICIT NONE
INTEGER,INTENT(IN) :: n
INTEGER,INTENT(INOUT),ALLOCATABLE,DIMENSION(:,:) :: table
DOUBLE PRECISION :: rows,a,b
INTEGER :: cnt
INTEGER :: i,j
a=fact(n+5)
b=fact(n)
rows=a/(b*24.0)
ALLOCATE(table(INT(rows),5))

DO j=1,INT(rows)
  DO i=1,5
    table(j,i)=0    
  END DO
END DO

cnt=1
call permute(n,5,cnt,table)
print *,'count=',cnt
DO j=1,INT(rows)
 !print *,(table(j,i),i=1,5)
END DO
END SUBROUTINE generatePermutations

END MODULE fun

PROGRAM energy
USE fun
IMPLICIT NONE
INTEGER :: n ! no of particles
REAL :: e,s
INTEGER,ALLOCATABLE,DIMENSION(:,:) :: table
REAL, PARAMETER :: pi=3.14159265359
INTEGER :: i,j
print *,'no of particles'; read(*,*),n
print *,'enter e'; read (*,*),e
call generatePermutations(n,table)

DO j=1,fact(n+4)/(fact(n)*fact(4))
  s=0
  DO i=1,5
    s=s+REAL(table(j,i))*REAL((i-1))
  END DO
  !print *,s
  IF (s==e*n) THEN
    print *,(table(j,i),i=1,5)
  END IF
END DO
END PROGRAM
